/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.redisson;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.redisson.cluster.ClusterConnectionManager;
import org.redisson.core.RExpirable;

import com.lambdaworks.redis.RedisConnection;

abstract class ClusterRedissonExpirable extends RedissonObject implements RExpirable {

	final ClusterConnectionManager connectionManager;

	ClusterRedissonExpirable(ClusterConnectionManager connectionManager, String name) {
		super(name);
		this.connectionManager = connectionManager;
	}

	@Override
	public boolean expire(final long timeToLive, final TimeUnit timeUnit) {
	    return new ClusterCommand<Boolean>( connectionManager ) {
			@Override
			public Boolean execute(RedisConnection connection) {
				return connection.expire( getName() , timeUnit.toSeconds( timeToLive ) );
			}
		}.run( getName() );
	}

	@Override
	public boolean expireAt(final long timestamp) {
	    return new ClusterCommand<Boolean>( connectionManager ) {
			@Override
			public Boolean execute(RedisConnection connection) {
				return connection.expireat( getName() , timestamp );
			}
		}.run( getName() );
	}

	@Override
	public boolean expireAt(final Date timestamp) {
	    return new ClusterCommand<Boolean>( connectionManager ) {
			@Override
			public Boolean execute(RedisConnection connection) {
				return connection.expireat( getName() , timestamp );
			}
		}.run( getName() );
	}

	@Override
	public boolean clearExpire() {
	    return new ClusterCommand<Boolean>( connectionManager ) {
			@Override
			public Boolean execute(RedisConnection connection) {
				return connection.persist( getName() );
			}
		}.run( getName() );
	}

	@Override
	public long remainTimeToLive() {
		return new ClusterCommand<Long>( connectionManager ) {
			@Override
			public Long execute(RedisConnection connection) {
				return connection.ttl( getName() );
			}
		}.run( getName() );
	}
}